<?php
	// set up database info
	$usr = "flytalk";
	$pwd = "ft1234";
	$db = "flytalk";
	$host = "yangjustine.startlogicmysql.com";

	// establish connection
	$connection = mysql_connect($host,$usr,$pwd);
	if (!$connection) { echo("ERROR: " . mysql_error() . "\n"); }
	
	// dummy sql statements
//	$sql = 'SELECT * FROM `form`';
	//$sql =  "SELECT user.username, form.img, form.type, form.time, form.thread_id FROM `form`,`user` WHERE user.uid = form.from_uid";
// "INSERT INTO `IsFriend` (`username1`, `username2`,`dateAdded`) VALUES ('". $username1 ."', '". $username2 ."',CURRENT_TIMESTAMP);";
// $sql_recToFriend = "SELECT App.name, Recommendation.message FROM `FriendRec`,`App`, `Recommendation` WHERE FriendRec.sender = '". $username ."' and FriendRec.recid = Recommendation.recid and Recommendation.appid = App.appid;";
	
	
	// get method
	$method = $_GET['method'];
	
	if($method == 'getFlightPost'){// get all posts from flight TAP001 and sorted by thread
		$sql = "SELECT user.username, user.img, form.type, form.text, form.time, form.thread_id, form.up, form.down FROM `form`,`user` WHERE user.uid = form.from_uid and (user.flight = 'TAP001' or user.official = 1) ORDER BY `time` DESC";
	}else if($method == 'getTerminalPost'){ // get all posts from terminal 1
		$sql = "SELECT user.username, user.img, form.type, form.text, form.time, form.thread_id, form.up, form.down FROM `form`,`user` WHERE user.uid = form.from_uid and (user.terminal = 1 or user.official = 1) ORDER BY `time` DESC";
	}else if($method == 'getLangPost'){
		$sql ="";
	}
	
    $posts = mysql_db_query($db,"$sql",$connection);
	$post_list = array();
	if (!$posts) {
    		echo("ERROR: " . mysql_error() . "\n$SQL\n"); 	
	}
	else{
		// multiple posts  
		$last = "";
		$lpost = "";
		while($row = mysql_fetch_array($posts))
		{
			 
			 $post_list[] = array(
                'from_user' => $row['username'],
                'image_url' => $row['img'],
                'text' => $row['text'],
                'type' => $row['type'],
				'date' => $row['time'],
				'thread' => $row['thread_id'],
				'down' => $row['down'],
				'up' => $row['up'],
            );      
		}
		
		// $cb = isset($_GET['callback']) ? $_GET['callback'] : '';
       
   		//  echo $cb . '({"results":' . json_encode($post_list) . '})';
		$callback = $_GET['callback'];

		if ($callback) {
    		header('Content-Type: text/javascript');
    		echo $callback . '({"results":' . json_encode($post_list) . '});';
			//echo $callback . '({"results":' . $sql. '});';
		} else {
    		header('Content-Type: application/x-json');
    		echo json_encode($post_list);
		}
	}

	//mysql_close($connection);

?>